package com.elitedatai.mchtest.mission.service.impl;

import com.elitedatai.mchtest.mission.entity.FlightMission;
import com.elitedatai.mchtest.mission.enums.MissionStatus;
import com.elitedatai.mchtest.mission.enums.MissionType;
import com.elitedatai.mchtest.mission.model.dto.FlightMissionDTO;
import com.elitedatai.mchtest.mission.repository.FlightMissionRepository;
import com.elitedatai.mchtest.mission.service.IFlightMissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 飞行任务服务实现类
 * 提供飞行任务的增删改查业务逻辑实现
 */
@Service
@Transactional
@Slf4j
public class FlightMissionServiceImpl implements IFlightMissionService {

    @Autowired
    private FlightMissionRepository flightMissionRepository;

    @Override
    public FlightMissionDTO createFlightMission(FlightMissionDTO flightMissionDTO) {
        if (flightMissionDTO == null) {
            throw new IllegalArgumentException("飞行任务数据不能为空");
        }

        if (!StringUtils.hasText(flightMissionDTO.getMissionId())) {
            throw new IllegalArgumentException("任务ID不能为空");
        }

        // 检查任务ID是否已存在
        if (flightMissionRepository.existsByMissionId(flightMissionDTO.getMissionId())) {
            throw new IllegalArgumentException("任务ID已存在: " + flightMissionDTO.getMissionId());
        }

        FlightMission entity = dtoToEntity(flightMissionDTO);
        FlightMission savedEntity = flightMissionRepository.save(entity);
        
        log.info("创建飞行任务成功，任务ID: {}", savedEntity.getMissionId());
        return entityToDto(savedEntity);
    }

    @Override
    public Optional<FlightMissionDTO> getFlightMissionById(Long id) {
        if (id == null) {
            return Optional.empty();
        }

        return flightMissionRepository.findById(id)
                .map(this::entityToDto);
    }

    @Override
    public Optional<FlightMissionDTO> getFlightMissionByMissionId(String missionId) {
        if (!StringUtils.hasText(missionId)) {
            return Optional.empty();
        }

        return flightMissionRepository.findByMissionId(missionId)
                .map(this::entityToDto);
    }

    @Override
    public List<FlightMissionDTO> getAllFlightMissions() {
        return flightMissionRepository.findAll()
                .stream()
                .map(this::entityToDto)
                .collect(Collectors.toList());
    }

    @Override
    public Page<FlightMissionDTO> getFlightMissionsPage(Pageable pageable) {
        return flightMissionRepository.findAll(pageable)
                .map(this::entityToDto);
    }

    @Override
    public FlightMissionDTO updateFlightMission(FlightMissionDTO flightMissionDTO) {
        if (flightMissionDTO == null || flightMissionDTO.getId() == null) {
            throw new IllegalArgumentException("飞行任务数据或ID不能为空");
        }

        Optional<FlightMission> existingEntityOpt = flightMissionRepository.findById(flightMissionDTO.getId());
        if (existingEntityOpt.isEmpty()) {
            throw new IllegalArgumentException("飞行任务不存在，ID: " + flightMissionDTO.getId());
        }

        FlightMission existingEntity = existingEntityOpt.get();
        
        // 更新字段
        if (StringUtils.hasText(flightMissionDTO.getMissionId())) {
            // 如果任务ID发生变化，需要检查新的任务ID是否已存在
            if (!flightMissionDTO.getMissionId().equals(existingEntity.getMissionId()) 
                && flightMissionRepository.existsByMissionId(flightMissionDTO.getMissionId())) {
                throw new IllegalArgumentException("任务ID已存在: " + flightMissionDTO.getMissionId());
            }
            existingEntity.setMissionId(flightMissionDTO.getMissionId());
        }
        
        if (flightMissionDTO.getMissionType() != null) {
            existingEntity.setMissionType(flightMissionDTO.getMissionType().getVal());
        }
        
        if (flightMissionDTO.getMissionStatus() != null) {
            existingEntity.setMissionStatus(flightMissionDTO.getMissionStatus().getVal());
        }

        FlightMission updatedEntity = flightMissionRepository.save(existingEntity);
        
        log.info("更新飞行任务成功，任务ID: {}", updatedEntity.getMissionId());
        return entityToDto(updatedEntity);
    }

    @Override
    public boolean deleteFlightMissionById(Long id) {
        if (id == null) {
            throw new IllegalArgumentException("ID不能为空");
        }

        if (!flightMissionRepository.existsById(id)) {
            throw new IllegalArgumentException("飞行任务不存在，ID: " + id);
        }

        flightMissionRepository.deleteById(id);

        if (flightMissionRepository.existsById(id)) {
            log.info("删除飞行任务失败，ID: {}", id);
            return false;
        }
        log.info("删除飞行任务成功，ID: {}", id);
        return true;
    }

    @Override
    public boolean deleteFlightMissionByMissionId(String missionId) {
        if (!StringUtils.hasText(missionId)) {
            throw new IllegalArgumentException("任务ID不能为空");
        }

        if (!flightMissionRepository.existsByMissionId(missionId)) {
            throw new IllegalArgumentException("飞行任务不存在，任务ID: " + missionId);
        }

        flightMissionRepository.deleteByMissionId(missionId);
        if (flightMissionRepository.existsByMissionId(missionId)) {
            log.info("删除飞行任务失败，任务ID: {}", missionId);
            return false;
        }
        log.info("删除飞行任务成功，任务ID: {}", missionId);
        return true;
    }

    @Override
    public void deleteFlightMissionsByIds(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            throw new IllegalArgumentException("ID列表不能为空");
        }

        List<FlightMission> existingMissions = flightMissionRepository.findAllById(ids);
        if (existingMissions.size() != ids.size()) {
            throw new IllegalArgumentException("部分飞行任务不存在");
        }

        flightMissionRepository.deleteAllById(ids);
        log.info("批量删除飞行任务成功，数量: {}", ids.size());
    }

    /**
     * 实体转DTO
     * @param entity 飞行任务实体
     * @return 飞行任务DTO
     */
    private FlightMissionDTO entityToDto(FlightMission entity) {
        if (entity == null) {
            return null;
        }

        return FlightMissionDTO.builder()
                .id(entity.getId())
                .missionId(entity.getMissionId())
                .missionType(MissionType.find(entity.getMissionType()))
                .missionStatus(MissionStatus.find(entity.getMissionStatus()))
                .createTime(entity.getCreateTime())
                .updateTime(entity.getUpdateTime())
                .build();
    }

    /**
     * DTO转实体
     * @param dto 飞行任务DTO
     * @return 飞行任务实体
     */
    private FlightMission dtoToEntity(FlightMissionDTO dto) {
        if (dto == null) {
            return null;
        }

        FlightMission entity = new FlightMission();
        entity.setId(dto.getId());
        entity.setMissionId(dto.getMissionId());
        
        if (dto.getMissionType() != null) {
            entity.setMissionType(dto.getMissionType().getVal());
        }
        
        if (dto.getMissionStatus() != null) {
            entity.setMissionStatus(dto.getMissionStatus().getVal());
        }

        return entity;
    }
}